package com.ubtechinc.cruzr.libai.honglauncher;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;
import com.github.pwittchen.reactivenetwork.library.rx2.Connectivity;
import com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork;
import com.jakewharton.rxbinding2.view.RxView;
import com.liulishuo.okdownload.DownloadContext;
import com.liulishuo.okdownload.DownloadContextListener;
import com.liulishuo.okdownload.DownloadListener;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.orhanobut.logger.Logger;
import com.ubtechinc.cruzr.libai.honglauncher.RecyclerViewHelper.HorizontalPageLayoutManager;
import com.ubtechinc.cruzr.libai.honglauncher.RecyclerViewHelper.PagingItemDecoration;
import com.ubtechinc.cruzr.libai.honglauncher.RecyclerViewHelper.PagingScrollHelper;

import com.ubtechinc.cruzr.libai.honglauncher.db.AppInfoEntity;
import com.ubtechinc.cruzr.libai.honglauncher.db.AppPictureEntity;
import com.ubtechinc.cruzr.libai.honglauncher.down.DownloadListenerSimple;
import com.ubtechinc.cruzr.libai.honglauncher.entity.HlyAppInfoEntity;
import com.ubtechinc.cruzr.libai.honglauncher.entity.HlyBackgroundEntity;
import com.ubtechinc.cruzr.libai.honglauncher.entity.HlyCustomInfoEntity;
import com.ubtechinc.cruzr.libai.honglauncher.entity.HlyDeptInfo;
import com.ubtechinc.cruzr.libai.honglauncher.http.HttpManager;
import com.ubtrobot.http.rest.URestException;
import com.ubtrobot.retrofit.adapter.urest.URestCall;
import com.ubtrobot.retrofit.adapter.urest.URestCallback;

import org.reactivestreams.Publisher;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;

import static com.ubtechinc.cruzr.libai.honglauncher.Constants.BACKGROUND_DOWNLOAD_URL;

/**
 * 活动签到 com.ubtechinc.cruzr.orgnizeactivities
 * 意见箱 com.ubtechinc.cruzr.suggestion
 * 咨询 com.ubtechinc.cruzr.behavior
 * 党建地图 com.ubtechinc.cruzr.partymap
 */
public class MainActivity extends AppCompatActivity implements AdminiListener, PagingScrollHelper.onPageChangeListener, LaunchAdapterItemClickListener {
    //    private RecyclerView recyclerView;
    //    private GridLayoutManager gridLayoutManager;
//private PageIndicate indicator;
//    private LaunchAdapter adapter;
    private int mLastX, mLastY;
    private boolean isDeleted = false;
    //    PagingScrollHelper scrollHelper = new PagingScrollHelper();
    private List<ItemData> appInfoList = new ArrayList<>();
    private final CompositeDisposable compositeDisposable = new CompositeDisposable();
    private ImageView iconOrganizeActivities;
    private ImageView iconBehavior;
    private ImageView iconPartMap;
    private ImageView iconSuggestion;
    private ImageView bgContainer;
    private TextView nameOrganizeActivities;
    private TextView nameBehavior;
    private TextView namePartMap;
    private TextView nameSuggestion;

    /**
     * 首页显示的APP的个数
     */
    private final static int FIRST_PAGE_APP_COUNT = 4;
    private Observable<HlyCustomInfoEntity> customInfoObservable;
    HorizontalPageLayoutManager horizontalPageLayoutManager;
    PagingItemDecoration pagingItemDecoration;
    /**
     * 是否是第一次下载背景图：需求每次开机下载一次（网络连接有变化，下载成功是设置为true)
     */
    private AtomicBoolean isFirstLoadRemoteResource = new AtomicBoolean(false);
    /**
     * 用来保存下载前使用的背景图的bitmap，在下载完成后进行回收
     */
    private Bitmap lastThemeBgBitmap;
    /**
     * 用来控制只有在设置完背景图后，才进行背景图下载，避免由于多线程造成的错乱。
     * 原因：initView()中设置背景图的速度可能慢于（下载背景图并进行设置背景）
     */
    private PublishSubject<Boolean> triggerBgDownload;
    private PublishSubject<Boolean> filterLoadFinish;
    private Observable<File> downBackgroundObservable;

    /**
     * 触发更新UI任务，主要用来更改背景图和icon样式。
     */
    private Observable<Boolean> startUpdateUiObservable;
    /**
     * 背景图片下载任务
     */
    private DownloadTask downloadBgTask;
    /**
     * 触发更新当前应用的所有信息，true 表示第一次加载，false表示有应用信息发生了改变。
     */
    private PublishSubject<Boolean> updateAppInfoObservable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_version_one);
        triggerBgDownload = PublishSubject.create();
        updateAppInfoObservable = PublishSubject.create();
        filterLoadFinish = PublishSubject.create();

        downBackgroundObservable = Observable.create(emitter -> {
            //http://p02mn0gfw.bkt.clouddn.com/test_bg_one.pn
            downloadBgTask = new DownloadTask.Builder(BACKGROUND_DOWNLOAD_URL, getParentFile(App.getContext()))
                    .setFilename(Constants.REMOTE_BG_NAME)
                    .setMinIntervalMillisCallbackProcess(16)
                    .setPassIfAlreadyCompleted(false)
                    .build();
            downloadBgTask.execute(new DownloadListenerSimple() {
                @Override
                public void taskCompleted(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause) {
                    Logger.i("父目录： " + getParentFile(App.getContext()) + "  下载的文件路径：" + task.getFile().getPath());
                    if (cause == EndCause.COMPLETED) {
                        emitter.onNext(task.getFile());
                        emitter.onComplete();
                    } else {
                        emitter.onError(realCause);
                    }
                }
            });
        });

        customInfoObservable = Observable.create(emitter -> {
            HlyCustomInfoEntity info = HttpManager.getInstance().getApiService().getCustomAppInfo("3932").execute();
            emitter.onNext(info);
            emitter.onComplete();
        });

        startUpdateUiObservable = ReactiveNetwork
                .observeNetworkConnectivity(this)
                .flatMap((Function<Connectivity, ObservableSource<Boolean>>)
                        connectivity -> Observable.just(isFirstLoadRemoteResource.get()))
                .cache()
                .share();

        initCache();
        initView();
        register();
    }


    @SuppressLint("CheckResult")
    private void initView() {
        HorizontalPageLayoutManager horizontalPageLayoutManager = new HorizontalPageLayoutManager(2, 4);
        PagingItemDecoration pagingItemDecoration = new PagingItemDecoration(this, horizontalPageLayoutManager);
        bgContainer = findViewById(R.id.iv_launch_main_bg);
        iconOrganizeActivities = findViewById(R.id.iv_icon_organize_activities);
        iconBehavior = findViewById(R.id.iv_icon_behavior);
        iconPartMap = findViewById(R.id.iv_icon_part_map);
        iconSuggestion = findViewById(R.id.iv_icon_suggestion);
        nameOrganizeActivities = findViewById(R.id.tv_app_name_organize_activities);
        nameBehavior = findViewById(R.id.tv_app_name_behavior);
        namePartMap = findViewById(R.id.tv_app_name_part_map);
        nameSuggestion = findViewById(R.id.tv_app_name_suggestion);
//        recyclerView = findViewById(R.id.main_app_list);
//        indicator = findViewById(R.id.main_page_indicate);
//        adapter = new LaunchAdapter(this, appInfoList);
//        recyclerView.setAdapter(adapter);
//        scrollHelper.setUpRecycleView(recyclerView);
//        scrollHelper.setOnPageChangeListener(this);
//        recyclerView.setHorizontalScrollBarEnabled(true);
//        recyclerView.setLayoutManager(horizontalPageLayoutManager);
//        recyclerView.addItemDecoration(pagingItemDecoration);
//        scrollHelper.updateLayoutManger();
//        scrollHelper.scrollToPosition(0);
        String lastBgFilePath = parentFile + File.separator + Constants.REMOTE_BG_NAME;
        //设置背景图--如果没有以前下载过的背景图，就使用默认的背景图，如果有则使用最近下载过的背景图（本地只保存
        //最新下载的背景图）。
        if (FileUtils.isFileExists(lastBgFilePath)) {
            compositeDisposable.add(Observable.just(lastBgFilePath)
                    .subscribeOn(Schedulers.io())
                    .map((Function<String, Drawable>) path -> {
                        lastThemeBgBitmap = ImageUtils.getBitmap(path);
                        return new BitmapDrawable(App.getContext().getResources(), lastThemeBgBitmap);
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(drawable -> {
                        bgContainer.setBackground(drawable);
                    }));
        } else {
            bgContainer.setBackgroundResource(R.drawable.launcher_background);
        }

        App.getDatabase().appPictureDao().getAllAppPicture()
                .subscribeOn(Schedulers.io())
                .map(appPictureEntities -> {
                    Map<String, Drawable> picMap = new HashMap<>(5);
                    for (AppPictureEntity appPic : appPictureEntities) {
                        Drawable drawable;
                        if (FileUtils.isFileExists(appPic.picture_value)) {
                            drawable = new BitmapDrawable(App.getContext().getResources(), ImageUtils.getBitmap(appPic.picture_value));
                            picMap.put(appPic.picture_key, drawable);
                        }
                    }
                    return picMap;
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(drawableMap -> {
                    for (Map.Entry<String, ImageView> entry : appIconMap.entrySet()) {
                      if (drawableMap.get(entry.getKey())!=null){
                          entry.getValue().setBackground(drawableMap.get(entry.getKey()));
                      }else {
                          entry.getValue().setBackgroundResource(appDefaultIconMap.get(entry.getKey()));
                      }
                    }
                }, throwable -> {

                });

//        compositeDisposable.add(App.getDatabase().appInfoDao().getAllAppInfo()
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(appInfoEntities -> {
//
//                }, throwable -> {
//                    throwable.printStackTrace();
//                }));
    }

    private final File parentFile = getParentFile(App.getContext());
    private final Map<String, ImageView> appIconMap = new HashMap<>();
    private final Map<String, Integer> appDefaultIconMap = new HashMap<>();

    public void initCache() {
        appIconMap.put(BuildConfig.APP_ID, bgContainer);
        appIconMap.put(Constants.APP_ID_ORGANIZE_ACTIVITIES, iconOrganizeActivities);
        appIconMap.put(Constants.APP_ID_BEHAVIOR, iconBehavior);
        appIconMap.put(Constants.APP_ID_PART_MAP, iconPartMap);
        appIconMap.put(Constants.APP_ID_SUGGESTION, iconSuggestion);

        appDefaultIconMap.put(BuildConfig.APP_ID, R.drawable.launcher_background);
        appDefaultIconMap.put(Constants.APP_ID_ORGANIZE_ACTIVITIES, R.drawable.icon_organize_activities_2);
        appDefaultIconMap.put(Constants.APP_ID_BEHAVIOR, R.drawable.icon_behavior_2);
        appDefaultIconMap.put(Constants.APP_ID_PART_MAP, R.drawable.icon_part_map_2);
        appDefaultIconMap.put(Constants.APP_ID_SUGGESTION, R.drawable.icon_suggestion_2);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mObserve = new AdministratorObserve();
        mObserve.initSecurityApi(this);

        compositeDisposable.add(
                RxView.clicks(iconOrganizeActivities).subscribe(o -> {

                }));

        compositeDisposable.add(RxView.clicks(iconBehavior).subscribe(o -> {

        }));

        compositeDisposable.add(RxView.clicks(iconPartMap).subscribe(o -> {
        }));

        compositeDisposable.add(RxView.clicks(iconSuggestion).subscribe(o -> {

        }));

        compositeDisposable.add(ReactiveNetwork
                .observeNetworkConnectivity(this)
                .flatMap((Function<Connectivity, ObservableSource<HlyCustomInfoEntity>>) connectivity -> customInfoObservable)
                .subscribeOn(Schedulers.io())
                .subscribe(hlyCustomInfoEntity -> {
                    HlyBackgroundEntity background = hlyCustomInfoEntity.getBackground();
                    List<HlyAppInfoEntity> appList = hlyCustomInfoEntity.getAppList();
                    List<AppPictureEntity> pictureInfo = new ArrayList<>();
                    DownloadContext.Builder builder = new DownloadContext.QueueSet()
                            .setParentPathFile(parentFile)
                            .setMinIntervalMillisCallbackProcess(300)
                            .commit();
//                    DownloadTask task = new DownloadTask.Builder(Constants.BACKGROUND_DOWNLOAD_URL, parentFile)
//                            .setFilename(Constants.REMOTE_BG_NAME)
//                            .build();
//                    builder.bindSetTask(task);
                    builder.bind(background.getBackgroundUrl()).setTag(BuildConfig.APPLICATION_ID);
                    for (HlyAppInfoEntity infoEntity : appList) {
                        builder.bind(infoEntity.getIconUrl()).setTag(infoEntity.getPackageName());
                    }
                    builder.setListener(new DownloadContextListener() {
                        @Override
                        public void taskEnd(@NonNull DownloadContext context,
                                            @NonNull DownloadTask task,
                                            @NonNull EndCause cause,
                                            @Nullable Exception realCause,
                                            int remainCount) {
                        }

                        @Override
                        public void queueEnd(@NonNull DownloadContext context) {
                            Log.i("MainActivity", "queueEnd 回调函数");
                            App.getAppExecutors().diskIO().execute(() -> App.getDatabase().appPictureDao().insertAll(pictureInfo));
                        }
                    });
                    DownloadContext context = builder.build();
                    context.startOnParallel(new DownloadListenerSimple() {
                        @Override
                        public void taskCompleted(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause) {
                            AppPictureEntity pictureEntity = new AppPictureEntity();
                            pictureEntity.picture_key = (String) task.getTag();
                            pictureEntity.picture_value = task.getFile().getPath();
                            pictureInfo.add(pictureEntity);
                            Log.i("MainActivity", "当前已下载的内容：" + task.getFile().getPath());
                        }
                    });
                }, throwable -> {

                }));

//        //下载背景图
//        compositeDisposable.add(
//                triggerBgDownload
//                        .filter(new Predicate<Boolean>() {
//                            @Override
//                            public boolean test(Boolean aBoolean) throws Exception {
//                                return isFirstLoadRemoteResource.get();
//                            }
//                        })
//                        .doOnDispose(() -> {
//                            if (downloadBgTask != null) {
//                                downloadBgTask.cancel();
//                            }
//                        })
//                        .subscribeOn(Schedulers.io())
//                        //只加载一次
//                        .filter(isFirst -> isFirst)
//                        .flatMap((Function<Boolean, ObservableSource<File>>) filterSuccess -> downBackgroundObservable)
//                        .map((Function<File, Drawable>) file ->
//                                new BitmapDrawable(App.getContext().getResources(), ImageUtils.getBitmap(file, 1920, 1080)))
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(drawable -> {
//                            isFirstLoadRemoteResource.compareAndSet(false, true);
//                            bgContainer.setBackground(drawable);
//                            //回收之前创建的bitmap
//                            if (lastThemeBgBitmap != null) {
//                                lastThemeBgBitmap.recycle();
//                                lastThemeBgBitmap = null;
//                            }
//                        }, throwable -> {
//                            if (downloadBgTask != null) {
//                                downloadBgTask.cancel();
//                            }
//                            throwable.printStackTrace();
//                        }));


//        compositeDisposable.add(updateAppInfoObservable.subscribeOn(Schedulers.io())
//                .flatMap((Function<Boolean, ObservableSource<List<AppInfoEntity>>>) isInit -> filterAppInfoObservable)
//                .map(filter -> {
//                    Logger.i("来自应用信息发生改变时的更新");
//                    List<AppInfoEntity> all = getAllAppInfo();
//                    List<AppInfoEntity> resultAppInfo = new ArrayList<>();
//                    for (AppInfoEntity origin : all) {
//                        boolean visibility = true;
//                        if (filter.size() != 0) {
//                            for (AppInfoEntity discard : filter) {
//                                if (origin.packagename.equals(discard.packagename)
//                                        || origin.activityname.equals(discard.activityname)) {
//                                    visibility = false;
//                                }
//                            }
//                        }
//                        if (visibility) {
//                            resultAppInfo.add(origin);
//                        }
//                    }
//                    return resultAppInfo;
//                })
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(this::updateAdapterData, throwable -> {
//
//                        }
//                )
//        );

//        /*
//         *当可见应用信息(数据库发生了改变）发生改变时
//         */
//        compositeDisposable.add(filterAppInfoObservable.map(
//                filter -> {
//                    Logger.i("来自数据库的更新");
//                    List<AppInfoEntity> all = getAllAppInfo();
//                    List<AppInfoEntity> resultAppInfo = new ArrayList<>();
//                    for (AppInfoEntity origin : all) {
//                        boolean visibility = true;
//                        if (filter != null && filter.size() != 0) {
//                            for (AppInfoEntity discard : filter) {
//                                if (origin.packagename.equals(discard.packagename)
//                                        || origin.activityname.equals(discard.activityname)) {
//                                    visibility = false;
//                                }
//                            }
//                        }
//                        if (visibility) {
//                            resultAppInfo.add(origin);
//                        }
//                    }
//                    return resultAppInfo;
//                }
//        ).subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(appInfoEntities -> {
//                    updateAdapterData(appInfoEntities);
//                    filterLoadFinish.onNext(true);
//                    filterLoadFinish.onComplete();
//                }, throwable -> {
//
//                }));
//
//
//        compositeDisposable.add(
//                filterLoadFinish.zipWith(startUpdateUiObservable, (aBoolean, aBoolean2) -> true)
//                        .map(isFirst -> AppInfoControlImp.getInstant().getVisitAppInfo())
//                        .observeOn(Schedulers.io())
//                        .subscribe(visits -> {
//                            List<AppInfoEntity> filterAppInfoList = new ArrayList<>();
//                            int app_index = 0;
//                            for (String discard : visits) {
//                                AppInfoEntity appInfo = new AppInfoEntity();
//                                appInfo.id = app_index;
//                                appInfo.packagename = discard.trim();
//                                filterAppInfoList.add(appInfo);
//                                app_index++;
//                            }
//                            App.getDatabase().runInTransaction(() -> {
//                                App.getDatabase().appInfoDao().deleteAll();
//                                App.getDatabase().appInfoDao().insertAll(filterAppInfoList);
//                            });
//
//                        }, throwable -> {
//                            Log.i("appInfoDao", "发生了错误");
//                            throwable.printStackTrace();
//                        })
//        );
    }

    @NonNull
    private List<AppInfoEntity> getAllAppInfo() throws PackageManager.NameNotFoundException {
        List<AppInfoEntity> all = new ArrayList<>();
        final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PackageManager pm = App.getContext().getApplicationContext().getPackageManager();
        List<ResolveInfo> resolveInfos = pm.queryIntentActivities(mainIntent, 0);
        for (ResolveInfo resolveInfo : resolveInfos) {
            String pkg = resolveInfo.activityInfo.packageName;
            String activityname = resolveInfo.activityInfo.name;
            AppInfoEntity info = new AppInfoEntity();
            info.packagename = pkg;
            info.activityname = activityname;
            info.iconname = null;
            info.appname = resolveInfo.loadLabel(pm).toString();
            info.isSystemApp = isSystemApp(pkg);
            all.add(info);
        }
        return all;
    }

    private Observable<List<AppInfoEntity>> filterAppInfoObservable =
            App.getDatabase().appInfoDao().getAllAppInfo().toObservable();

    private static File getParentFile(@NonNull Context context) {
        final File externalSaveDir = context.getApplicationContext().getExternalCacheDir();
        if (externalSaveDir == null) {
            return context.getCacheDir();
        } else {
            return externalSaveDir;
        }
    }

    private List<AppInfoEntity> mAppList = new ArrayList<>();
    private AdministratorObserve mObserve;
    private long mStartTime;


    public void reLoadApp() {
        //更新应用信息
//        updateAppInfoObservable.onNext(false);
    }


    @Override
    public void onEnterAdmini() {
        Logger.e("enter onEnterAdmini");
        mStartTime = System.currentTimeMillis();
    }

    @Override
    public void onExitAdmini() {
        Logger.e("exit onExitAdmini");
        mStartTime = System.currentTimeMillis();
    }

    public List<AppInfoEntity> getData() {
        return mAppList;
    }


    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(BroadcastRec);
        unregisterReceiver(BroadcastKeybroad);
        compositeDisposable.clear();
    }

//    @Override
//    public boolean dispatchTouchEvent(MotionEvent event) {
//        switch (event.getAction()) {
//            case MotionEvent.ACTION_DOWN:
//                isDeleted = isAppDeleteState();
//                mLastX = (int) event.getX();
//                mLastY = (int) event.getY();
//                break;
//            case MotionEvent.ACTION_UP:
//            case MotionEvent.ACTION_CANCEL:
//                int x = (int) event.getX();
//                int y = (int) event.getY();
//                int distancex = x - mLastX;
//                int distancey = y - mLastY;
//                if (Math.abs(distancex) < 5 && Math.abs(distancey) < 5) {
//                    exitDeleteState(isDeleted);
//                }
//                break;
//            default:
//                break;
//        }
//        return super.dispatchTouchEvent(event);
//    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return keyCode == KeyEvent.KEYCODE_BACK || super.onKeyDown(keyCode, event);
    }

    private void register() {
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        intentFilter.addAction(UbtCantans.KEYBROAD_CHANGE);
        intentFilter.addAction(UbtCantans.RESET_NAVIGATION_BAR);
        intentFilter.addDataScheme("package");
        registerReceiver(BroadcastRec, intentFilter);
        IntentFilter intentFilter1 = new IntentFilter(UbtCantans.KEYBROAD_CHANGE);
        intentFilter1.addAction(UbtCantans.KEYBROAD_CHANGE);
        registerReceiver(BroadcastKeybroad, intentFilter1);
    }

    public final BroadcastReceiver BroadcastRec = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            LogUtils.e("收到的广播  = " + intent.getAction());
            if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction()) || Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
                reLoadApp();
            }
        }
    };
    public final BroadcastReceiver BroadcastKeybroad = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (UbtCantans.RESET_NAVIGATION_BAR.equals(intent.getAction())) {

            } else if (UbtCantans.KEYBROAD_CHANGE.equals(intent.getAction())) {

            }
        }
    };

    public void onclick(View v) {
        Intent intent = new Intent(this, App.class);
        startActivity(intent);
//        adapter.notifyDataSetChanged();
    }

    private void updateAdapterData(List<AppInfoEntity> appList) {
        appInfoList.clear();
        List<AppInfoEntity> firstPageAppInfoList = new ArrayList<>();
        for (int i = 0; i < FIRST_PAGE_APP_COUNT; i++) {
            firstPageAppInfoList.add(appList.get(i));
        }
        ItemData headerViewData = new ItemData(0, firstPageAppInfoList);
        appInfoList.add(headerViewData);
        for (int j = FIRST_PAGE_APP_COUNT; j < appList.size(); j++) {
            ItemData commonItemData = new ItemData(1, appList.get(j));
            appInfoList.add(commonItemData);
        }
//        adapter.notifyDataSetChanged();
    }

    @Override
    public void onPageChange(int index) {
//        if (scrollHelper != null) {
//            indicator.reFreshPage(this, index, scrollHelper.getPageCount());
//        }
    }

    /**
     * item的点击事件
     *
     * @param v             view
     * @param appInfoEntity 应用数据
     * @param position      点击位置
     */
    @Override
    public void onCLickEvent(View v, AppInfoEntity appInfoEntity, int position) {
        openActivity(appInfoEntity.packagename, appInfoEntity.activityname, false);
    }

    /**
     * item的长按事件
     *
     * @param v             view
     * @param appInfoEntity 应用信息
     * @param position      点击位置
     */
    @Override
    public void onLongCLickEvent(View v, AppInfoEntity appInfoEntity, int position) {

    }

    public void openActivity(String pkg, String activityname, boolean isthird) {
        if (TextUtils.isEmpty(pkg) || TextUtils.isEmpty(activityname)) {
            return;
        }
        Log.e("launcher", "rqh do action position = " + activityname);
        try {
            ComponentName componentName = new ComponentName(pkg, activityname);
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.setComponent(componentName);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            App.getContext().startActivity(intent);
            if (isthird) {
                //  boolean isrecord = ThirdStateHelper.getUsesPermission(LauncherApplication.getContext(), pkg);
                //  LogUtils.e("rqh getUsesPermission  isrecord = " + isrecord);
                // if (isrecord) {
//                mStatusManager.setThirdAppStatus(); // 所有应用都需要加状态
//                mAppListener.onThirdAppOpen();
                // }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static boolean isSystemApp(String pname) throws PackageManager.NameNotFoundException {
        if (TextUtils.isEmpty(pname)) {
            return false;
        }
        PackageInfo pInfo = App.getContext().getApplicationContext().getPackageManager().getPackageInfo(pname, 0);
        return isSystemApp(pInfo) || isSystemUpdateApp(pInfo);
    }

    private static boolean isSystemApp(PackageInfo pInfo) {
        return ((pInfo.applicationInfo.flags & android.content.pm.ApplicationInfo.FLAG_SYSTEM) != 0);
    }

    private static boolean isSystemUpdateApp(PackageInfo pInfo) {
        return ((pInfo.applicationInfo.flags & android.content.pm.ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0);
    }

    public static String getSettingsStringValue(Context mContext, String key, String defaultValue) {
        ContentResolver cr = mContext.getContentResolver();
        Uri uri = Uri.parse("content://com.ubtechinc.settings.provider/CruiserSettings");
        String info = defaultValue;
        Bundle bundle = cr.call(uri, Constants.CALL_METHOD_GET_SETTING, key, null);
        if (bundle != null) {
            info = bundle.getString("value");
        }
        if (info != null) {
            return info;
        } else {
            return defaultValue;
        }
    }
}
